package cn.pugle.mianshi.thread1To10;

import java.util.concurrent.atomic.AtomicInteger;

import static cn.pugle.mianshi.thread1To10.Constant.MAX;

/**
 * @author tzp
 * @since 2018/2/8
 */
public class PrintToTen4 implements Runnable {
    private AtomicInteger count = new AtomicInteger(1);

    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " Hello World");

        Thread thread1 = new Thread(() -> {
            while (count.get() <= MAX) {
                int ct = count.get();
                if (ct % 2 == 0 && ct <= MAX) {
                    System.out.println(Thread.currentThread() + " " + ct);
                    count.getAndIncrement();
                }
                Thread.yield();
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            while (count.get() <= MAX) {
                int ct = count.get();
                if (ct % 2 == 1 && ct <= MAX) {
                    System.out.println(Thread.currentThread() + " " + ct);
                    count.getAndIncrement();
                }
                Thread.yield();
            }
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new PrintToTen4().run();
    }
}
